import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Input, Button, Radio, message, Spin } from "antd";
import { RightOutlined, CopyOutlined, DownloadOutlined } from "@ant-design/icons";

import "./index.css";
import { getApiUrl } from "../../config/api";

const { TextArea } = Input;

// 创作模板数据
const templates = [
  {
    icon: "📝",
    title: "工作",
    items: [
      { name: "工作汇报", desc: "编写工作进展汇报" },
      { name: "会议记录", desc: "整理会议要点和决议" },
      { name: "工作计划", desc: "制定详细的工作计划" },
    ],
  },
  {
    icon: "💼",
    title: "商业营销",
    items: [
      { name: "产品文案", desc: "编写产品介绍和亮点" },
      { name: "营销方案", desc: "策划营销活动方案" },
      { name: "品牌故事", desc: "创作品牌故事文案" },
    ],
  },
  {
    icon: "📚",
    title: "学习教育",
    items: [
      { name: "课程大纲", desc: "设计课程教学大纲" },
      { name: "教学计划", desc: "制定教学活动计划" },
      { name: "学习笔记", desc: "整理知识点笔记" },
    ],
  },
  {
    icon: "📱",
    title: "社媒文案",
    items: [
      { name: "微博文案", desc: "创作吸引人的微博内容" },
      { name: "公众号文章", desc: "撰写公众号推文" },
      { name: "短视频脚本", desc: "编写视频内容脚本" },
    ],
  },
  {
    icon: "✍️",
    title: "文学艺术",
    items: [
      { name: "小说创作", desc: "创作小说情节和内容" },
      { name: "诗歌创作", desc: "创作富有意境的诗歌" },
      { name: "散文随笔", desc: "书写生活感悟随笔" },
    ],
  },
  {
    icon: "🎨",
    title: "图像创作",
    items: [
      { name: "产品渲染", desc: "生成产品展示图片" },
      { name: "场景设计", desc: "创作特定场景图片" },
      { name: "插画创作", desc: "生成创意插画作品" },
    ],
  },
];

export const CreationPage = () => {
  const navigate = useNavigate();
  const [prompt, setPrompt] = useState("");
  const [generating, setGenerating] = useState(false);
  const [messages, setMessages] = useState([]);
  const [expandedCategories, setExpandedCategories] = useState(new Set());
  const [selectedModel, setSelectedModel] = useState("doubao");
  const [imageLoading, setImageLoading] = useState(false);
  const [generatedImage, setGeneratedImage] = useState(null);
  const [imageModel, setImageModel] = useState("qianfan"); // 添加图像模型状态

  const handleBack = () => {
    navigate("/chat");
  };

  const handleKeyPress = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleGenerate();
    }
  };

  const toggleCategory = (title) => {
    const newExpanded = new Set(expandedCategories);
    if (newExpanded.has(title)) {
      newExpanded.delete(title);
    } else {
      newExpanded.add(title);
    }
    setExpandedCategories(newExpanded);
  };

  const handleGenerate = async () => {
    if (!prompt.trim()) {
      message.warning("请输入创作提示词");
      return;
    }

    // 判断是否是图像创作
    if (prompt.startsWith("生成一张")) {
      await handleImageGeneration(prompt);
      return;
    }

    const userMessage = { type: "user", content: prompt };
    setMessages(prev => [...prev, userMessage]);
    
    setGenerating(true);
    try {
      const token = localStorage.getItem("token");
      const cleanToken = token.replace(/['"]+/g, "");
      
      const response = await fetch(getApiUrl('/api/chat/query'), {
        method: "POST",
        headers: {
          Authorization: `Bearer ${cleanToken}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ 
          prompt, 
          model: selectedModel  // 使用选择的模型
        }),
      });

      const result = await response.json();
      if (result.ok) {
        const aiMessage = { type: "ai", content: result.data };
        setMessages(prev => {
          const newMessages = [...prev, aiMessage];
          // 在状态更新的回调中执行滚动
          requestAnimationFrame(() => {
            const chatContainer = document.querySelector(".chat-container");
            if (chatContainer) {
              chatContainer.scrollTop = chatContainer.scrollHeight;
            }
          });
          return newMessages;
        });
        setPrompt("");
      }
    } catch (error) {
      console.error("AI 创作失败:", error);
      message.error("生成失败，请稍后重试");  // 使用 message 替换 messageApi
    } finally {
      setGenerating(false);
    }
  };

  // 添加图像生成处理函数
  const handleImageGeneration = async (prompt) => {
    setImageLoading(true);
    try {
      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');
      
      const response = await fetch(getApiUrl('/api/image/generate'), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cleanToken}`
        },
        body: JSON.stringify({ 
          prompt,
          model: imageModel  // 添加模型参数
        })
      });

      console.log('服务器响应状态:', response.status);
      const result = await response.json();
      console.log('服务器响应数据:', result);

      if (result.success) {
        setGeneratedImage(result.data);
        const userMessage = { type: "user", content: prompt };
        const aiMessage = { type: "ai", content: "图片已生成" };
        setMessages(prev => {
          const newMessages = [...prev, userMessage, aiMessage];
          // 在状态更新的回调中执行滚动
          requestAnimationFrame(() => {
            const chatContainer = document.querySelector(".chat-container");
            if (chatContainer) {
              chatContainer.scrollTop = chatContainer.scrollHeight;
            }
          });
          return newMessages;
        });
        message.success('图像生成成功！');

        // 添加滚动到底部的逻辑
        setTimeout(() => {
          const chatContainer = document.querySelector(".chat-container");
          if (chatContainer) {
            chatContainer.scrollTop = chatContainer.scrollHeight;
          }
        }, 100);
      } else {
        throw new Error(result.message || '生成失败');
      }
    } catch (error) {
      console.error('图像生成详细错误:', error);
      message.error('图像生成失败，请重试');
    } finally {
      setImageLoading(false);
    }
  };

  // 添加下载图片函数
  const handleDownloadImage = async () => {
    try {
      const response = await fetch(generatedImage);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `AI生成图片_${new Date().getTime()}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      message.success('图片下载成功');
    } catch (error) {
      console.error('图片下载失败:', error);
      message.error('图片下载失败，请重试');
    }
  };

  return (
    <div className="creation-page">
      <div className="creation-sidebar">
        <div className="sidebar-header">
          <h2>AI创作</h2>
        </div>
        <div className="sidebar-menu">
          {templates.map((category, index) => (
            <div key={index} className="menu-category">
              <div
                className={`category-title ${
                  expandedCategories.has(category.title) ? "expanded" : ""
                }`}
                onClick={() => toggleCategory(category.title)}
              >
                <span className="category-icon">{category.icon}</span>
                <span>{category.title}</span>
                <RightOutlined className="arrow-icon" />
              </div>
              {expandedCategories.has(category.title) && (
                <div className="category-items">
                  {category.items.map((item, i) => (
                    <div
                      key={i}
                      className="menu-item"
                      onClick={() => {
                        const prefix =
                          category.title === "图像创作"
                            ? "生成一张"
                            : "帮我写一篇";
                        setPrompt(`${prefix}${item.name}...`);
                      }}
                    >
                      {item.name}
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      <div className="creation-main">
        <div className="creation-header">
          <div className="back-button" onClick={handleBack}>
            <span className="back-arrow">‹</span>
            <span>返回</span>
          </div>
        </div>

        <div className="creation-scroll-area">
          {/* 添加图像显示区域 */}
          <div className="image-generation-area">
            {imageLoading && <Spin size="large" />}
            {generatedImage && (
              <div className="generated-image">
                <img src={generatedImage} alt="AI生成的图像" />
                <Button
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={handleDownloadImage}
                  className="download-button"
                >
                  下载图片
                </Button>
              </div>
            )}
          </div>
          {messages.length === 0 ? (
            <div className="intro-section">
              <div className="intro-header">
                <h2>AI 创作助手</h2>
                <p>让 AI 为您的创作提供灵感和帮助</p>
              </div>
              <div className="intro-features">
                <div className="feature-item">
                  <div className="feature-icon">🚀</div>
                  <div className="feature-content">
                    <h3>多模型协同</h3>
                    <p>同时调用多个 AI 模型，优化创作结果</p>
                  </div>
                </div>
                <div className="feature-item">
                  <div className="feature-icon">💡</div>
                  <div className="feature-content">
                    <h3>智能优化</h3>
                    <p>自动整理和优化内容，使其更加连贯完整</p>
                  </div>
                </div>
                <div className="feature-item">
                  <div className="feature-icon">📚</div>
                  <div className="feature-content">
                    <h3>丰富模板</h3>
                    <p>提供多种创作场景和模板供您选择</p>
                  </div>
                </div>
              </div>
              <div className="intro-guide">
                <h3>开始创作</h3>
                <ol>
                  <li>从左侧选择创作类型</li>
                  <li>输入您的创作需求</li>
                  <li>点击开始创作按钮</li>
                  <li>等待 AI 生成结果</li>
                </ol>
              </div>
            </div>
          ) : (
            <div className="chat-container">
              {messages.map((message, index) => (
                <div key={index} className={`message ${message.type}-message`}>
                  <div className="message-content">{message.content}</div>
                  {message.type === "ai" && (
                    <Button
                      type="text"
                      icon={<CopyOutlined />}
                      onClick={() => {
                        navigator.clipboard.writeText(message.content);
                        message.success("已复制到剪贴板");  // 使用 message 替换 messageApi
                      }}
                      className="copy-button"
                    >
                      复制
                    </Button>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="prompt-area">
          <div className="prompt-main">
            <div className="model-selector">
              {prompt.startsWith("生成一张") ? (
                <Radio.Group value={imageModel} onChange={e => setImageModel(e.target.value)}>
                  <Radio.Button value="qianfan">千帆文生图</Radio.Button>
                </Radio.Group>
              ) : (
                <Radio.Group value={selectedModel} onChange={e => setSelectedModel(e.target.value)}>
                  <Radio.Button value="doubao">豆包 AI</Radio.Button>
                  <Radio.Button value="deepseek">Deepseek</Radio.Button>
                  <Radio.Button value="doubao+deepseek">双模型</Radio.Button>
                  <Radio.Button value="qianfan">千帆文生图</Radio.Button>
                </Radio.Group>
              )}
            </div>
            <TextArea
              placeholder="输入创作提示词，让AI帮我创作..."
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              onKeyPress={handleKeyPress}
              disabled={generating}
              autoSize={{ minRows: 1, maxRows: 4 }}
            />
            <Button
              type="primary"
              onClick={handleGenerate}
              loading={generating}
              className="generate-button"
            >
              开始创作
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};
